package picol.outputmanager;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.Reader;
import picol.view.View;

/**
 * Gestion du flux de sortie
 * @author Aurélien Marcel - Julien Sanderson
 */
public class POutputStream extends OutputStream {

    private PipedOutputStream out = new PipedOutputStream();
    private Reader reader;
    private View view;

    public POutputStream(View _view) throws IOException {
        PipedInputStream in = new PipedInputStream(out);
        this.reader = new InputStreamReader(in);
        this.view = _view;
    }

    public void write(int i) throws IOException {
        out.write(i);
    }

    @Override
    public void write(byte[] bytes, int i, int i1) throws IOException {
        out.write(bytes, i, i1);
    }

    @Override
    public void flush() throws IOException {
        if (reader.ready()) {
            char[] chars = new char[1024];
            int n = reader.read(chars);

            String txt = new String(chars, 0, n);
            view.writeOutput(txt);
        }
    }
}
